# 搜索关键词然后点开下载附件

from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from openpyxl import Workbook


def parse_row(row):
    cells = row.find_elements(By.XPATH, "./td")

    values = [cell.text for cell in cells]
    return values


def write_to_xlsx(file_path, data):
    wb = Workbook()
    ws = wb.active
    for row in data:
        ws.append(row)

    # 保存文件
    wb.save(file_path)
    print("数据已写入 output.xlsx")


class Downloader:
    def __init__(self):
        self.driver = self.open_login_page()
        pass

    def open_login_page(self):
        # 指定Firefox的路径，例如在Windows上：
        firefox_path = "/opt/apps/org.mozilla.firefox-nal/files/firefox-nal/firefox"

        # 使用Service来设置路径
        # service = Service(executable_path="./geckodriver", firefox_binary=firefox_path)

        opt = Options()
        opt.binary_location = firefox_path

        sv = Service("/home/angela/app//geckodriver", log_output="gecko.log")
        # 设置浏览器驱动（需要下载对应浏览器的驱动）
        driver = webdriver.Firefox(service=sv, options=opt)  # 或 Firefox(), Edge() 等

        # 打开登录页面
        driver.get("http://oa.yuxi.cn/OA/LEAP/Login/5304/BOA/Login.html?lid=35FGfBeM")

        # 找到用户名和密码输入框并输入信息
        username = driver.find_element(By.ID, "txt_flag")  # 或 By.ID, By.XPATH等
        password = driver.find_element(By.ID, "txt_pwd")

        username.send_keys("fgwzp1")
        password.send_keys("Sep91700")

        # 提交表单（找到登录按钮并点击）
        login_button = driver.find_element(By.ID, "btn_login")
        login_button.click()

        time.sleep(3)

        return driver

    def search_value(self, keyword):
        search_input = self.driver.find_element(
            By.CSS_SELECTOR, "[ut=searchKeywords_topbar]"
        )
        search_input.send_keys(keyword)

        search_enter = self.driver.find_element(
            By.CSS_SELECTOR, "[ut=searchbutton_topbar]"
        )

        search_enter.click()

        time.sleep(3)

        print("搜索结果已显示")

        all_result = []
        for i in range(4):
            res = self.save_table_content(False)
            print("1dmu", res)
            all_result.extend(res)
            print(f"下一页 {i + 1}")
            next = self.driver.find_element(By.CSS_SELECTOR, "[ctf=table_page_next]")
            next.click()
            time.sleep(2)

        write_to_xlsx(f"{keyword}_搜索结果.xlsx", all_result)

    def save_table_content(self, only_title=True):
        """找到当前页的结果区域，将内容返回"""
        tbl = self.driver.find_element(By.CLASS_NAME, "searchresultsign")

        rows = tbl.find_elements(By.XPATH, "./tbody//tr")
        res = [parse_row(row) for row in rows]

        if only_title:
            return res

        tds = tbl.find_elements(By.XPATH, "./tbody//tr/td[2]")
        for td in tds:
            self.open_one_and_download(td)

    def open_one_and_download(self, elm):
        print(f"打开 {elm.text}")

        elm.click()

        all_windows = self.driver.window_handles
        self.driver.switch_to.window(all_windows[-1])

        new_url = self.driver.current_url
        print("新标签页网址", new_url)

        WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, "[ut=alluploadbtn]"))
        )

        bao = self.driver.find_element(By.CSS_SELECTOR, "[ut=alluploadbtn]")
        all_down = bao.find_element(By.XPATH, "./div/a")

        WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable(all_down))

        print("点击下载")

        all_down.click()
        time.sleep(3)

        self.driver.close()
        self.driver.switch_to.window(all_windows[0])

        time.sleep(3)


def main():
    dod = Downloader()
    dod.search_value("统计信息")

    # 完成后关闭浏览器
    dod.driver.quit()


if __name__ == "__main__":
    main()
